package cn.ming.wfchat.app.me.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.baidu.idl.face.platform.FaceConfig;
import com.baidu.idl.face.platform.FaceEnvironment;
import com.baidu.idl.face.platform.FaceSDKManager;
import com.baidu.idl.face.platform.LivenessTypeEnum;
import com.baidu.idl.face.platform.listener.IInitCallback;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.ming.wfchat.R;
import cn.ming.wfchat.app.AppService;
import cn.ming.wfchat.app.me.activity.model.CertificationListbean;
import cn.ming.wfchat.kit.WfcBaseActivity;
import cn.ming.wfchat.kit.dialog.LoadDialog;
import cn.ming.wfchat.kit.net.SimpleCallback;
import cn.ming.wfchat.kit.utils.Tools;

/**
 * 实名认证
 */
public class RealNameActivity extends WfcBaseActivity {


    @BindView(R.id.et_number)
    EditText etNumber;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.tv_next)
    TextView tvNext;
    // 动作活体条目集合
    public List<LivenessTypeEnum> livenessList = new ArrayList<>();
    private LoadDialog loadDialog;

    @Override
    protected void afterViews() {
        super.afterViews();
        initDate();
        setTitle("实名认证");
        certificationList();
        addActionLive();

    }

    @Override
    protected int contentLayout() {
        return R.layout.activity_real_name;
    }

    void initDate() {
        loadDialog = new LoadDialog(this, true, "处理中");
        requestPermissions(99);
    }


    @OnClick(R.id.tv_next)
    void sendRedpage() {
        if (TextUtils.isEmpty(etName.getText().toString().trim())) {
            Tools.showToast(RealNameActivity.this, "请输入姓名");
            return;
        }
        if (TextUtils.isEmpty(etNumber.getText().toString().trim())) {
            Tools.showToast(RealNameActivity.this, "请输入证件号码");
            return;
        }
        if (etNumber.getText().toString().trim().length() != 18) {
            Tools.showToast(RealNameActivity.this, "请输入18位身份证号码");
            return;
        }
        initLicense();
    }

    void certificationList() {
        AppService.Instance().certificationList(new AppService.CertificationListCallback() {
            @Override
            public void onUiSuccess(CertificationListbean redPageListBean) {
                if (TextUtils.equals(redPageListBean.getStatus(), "SUCCESS")) {
                    etName.setText(redPageListBean.getRealName());
                    etNumber.setText(redPageListBean.getIdentitycardNumber());
                    etNumber.setEnabled(false);
                    etName.setEnabled(false);
                    tvNext.setVisibility(View.GONE);
                }
            }

            @Override
            public void onUiFailure(int code, String msg) {

            }
        });
    }

    private void addActionLive() {
        // 根据需求添加活体动作
        livenessList.clear();
        livenessList.add(LivenessTypeEnum.Eye);
        livenessList.add(LivenessTypeEnum.Mouth);
        livenessList.add(LivenessTypeEnum.HeadRight);
//        ExampleApplication.livenessList.add(LivenessTypeEnum.HeadLeft);
//        ExampleApplication.livenessList.add(LivenessTypeEnum.HeadUp);
//        ExampleApplication.livenessList.add(LivenessTypeEnum.HeadDown);
//        ExampleApplication.livenessList.add(LivenessTypeEnum.HeadLeftOrRight);
        setFaceConfig();
    }

    // 请求权限
    public void requestPermissions(int requestCode) {
        try {
            if (Build.VERSION.SDK_INT >= 23) {
                ArrayList<String> requestPerssionArr = new ArrayList<>();
                int hasCamrea = checkSelfPermission(Manifest.permission.CAMERA);
                if (hasCamrea != PackageManager.PERMISSION_GRANTED) {
                    requestPerssionArr.add(Manifest.permission.CAMERA);
                }

                int hasSdcardRead = checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
                if (hasSdcardRead != PackageManager.PERMISSION_GRANTED) {
                    requestPerssionArr.add(Manifest.permission.READ_EXTERNAL_STORAGE);
                }

                int hasSdcardWrite = checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                if (hasSdcardWrite != PackageManager.PERMISSION_GRANTED) {
                    requestPerssionArr.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                }
                // 是否应该显示权限请求
                if (requestPerssionArr.size() >= 1) {
                    String[] requestArray = new String[requestPerssionArr.size()];
                    for (int i = 0; i < requestArray.length; i++) {
                        requestArray[i] = requestPerssionArr.get(i);
                    }
                    requestPermissions(requestArray, requestCode);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 参数配置方法
     */
    private void setFaceConfig() {
        FaceConfig config = FaceSDKManager.getInstance().getFaceConfig();
        // SDK初始化已经设置完默认参数（推荐参数），也可以根据实际需求进行数值调整
        // 设置可检测的最小人脸阈值
        config.setMinFaceSize(FaceEnvironment.VALUE_MIN_FACE_SIZE);
        // 设置可检测到人脸的阈值
        config.setNotFaceValue(FaceEnvironment.VALUE_NOT_FACE_THRESHOLD);
        // 设置模糊度阈值
        config.setBlurnessValue(FaceEnvironment.VALUE_BLURNESS);
        // 设置光照阈值（范围0-255）
        config.setBrightnessValue(FaceEnvironment.VALUE_BRIGHTNESS);
        // 设置遮挡阈值
        config.setOcclusionValue(FaceEnvironment.VALUE_OCCLUSION);
        // 设置人脸姿态角阈值
        config.setHeadPitchValue(FaceEnvironment.VALUE_HEAD_PITCH);
        config.setHeadYawValue(FaceEnvironment.VALUE_HEAD_YAW);
        // 设置闭眼阈值
        config.setEyeClosedValue(FaceEnvironment.VALUE_CLOSE_EYES);
        // 设置图片缓存数量
        config.setCacheImageNum(FaceEnvironment.VALUE_CACHE_IMAGE_NUM);
        // 设置口罩判断开关以及口罩阈值
        config.setOpenMask(FaceEnvironment.VALUE_OPEN_MASK);
        config.setMaskValue(FaceEnvironment.VALUE_MASK_THRESHOLD);
        // 设置活体动作，通过设置list，LivenessTypeEunm.Eye, LivenessTypeEunm.Mouth,
        // LivenessTypeEunm.HeadUp, LivenessTypeEunm.HeadDown, LivenessTypeEunm.HeadLeft,
        // LivenessTypeEunm.HeadRight, LivenessTypeEunm.HeadLeftOrRight
        config.setLivenessTypeList(livenessList);
        // 设置动作活体是否随机
        config.setLivenessRandom(true);
        // 设置开启提示音
        config.setSound(true);
        // 原图缩放系数
        config.setScale(FaceEnvironment.VALUE_OCCLUSION);
        // 抠图高的设定，为了保证好的抠图效果，我们要求高宽比是4：3，所以会在内部进行计算，只需要传入高即可
        config.setCropHeight(FaceEnvironment.VALUE_CROP_HEIGHT);
        // 抠图人脸框与背景比例
        config.setEnlargeRatio(FaceEnvironment.VALUE_CROP_ENLARGERATIO);
        // 加密类型，0：Base64加密，上传时image_sec传false；1：百度加密文件加密，上传时image_sec传true
        config.setSecType(FaceEnvironment.VALUE_SEC_TYPE);
        FaceSDKManager.getInstance().setFaceConfig(config);

    }

    private void initLicense() {
        // 为了android和ios 区分授权，appId=appname_face_android ,其中appname为申请sdk时的应用名
        // 应用上下文
        // 申请License取得的APPID
        // assets目录下License文件名
        FaceSDKManager.getInstance().initialize(RealNameActivity.this, "aeroplane-face-android",
                "idl-license.face-android", new IInitCallback() {
                    @Override
                    public void initSuccess() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Tools.showToast(RealNameActivity.this, "初始化成功");
                                Intent intent = new Intent(RealNameActivity.this, FaceLivenessExpActivity.class);
                                startActivityForResult(intent, 100);
                            }
                        });
                    }

                    @Override
                    public void initFailure(final int errCode, final String errMsg) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Tools.showToast(RealNameActivity.this, "初始化失败 = " + errCode + ", " + errMsg);
                            }
                        });
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == 100) {
            certificationSave(data.getStringExtra("mBmpStr"));
        }
    }

    void certificationSave(String bmpStr) {
        loadDialog.show();
        AppService.Instance().certificationSave(etNumber.getText().toString().trim(), etName.getText().toString().trim(), bmpStr,
                new SimpleCallback() {
                    @Override
                    public void onUiSuccess(Object o) {
                        loadDialog.dismiss();
                        Tools.showToast(RealNameActivity.this, "认证成功");
                        finish();

                    }

                    @Override
                    public void onUiFailure(int code, String msg) {
                        loadDialog.dismiss();
                        Tools.showToast(RealNameActivity.this, msg);
                    }
                });
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        boolean flag = false;
        for (int i = 0; i < permissions.length; i++) {
            if (PackageManager.PERMISSION_GRANTED == grantResults[i]) {
                flag = true;
            }
        }
    }

}
